package top.rainbowecho.gateway.security.support;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import top.rainbowecho.common.domain.shared.vo.ResponseResult;
import top.rainbowecho.common.util.CommonUtil;
import top.rainbowecho.common.util.ResultKey;
import top.rainbowecho.common.util.ResultParamFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 认证失败处理器，以json形式返回失败信息
 *
 * @author rainbow
 * @since 2019/12/14 14:08
 */
@Component
@Slf4j
public class JsonAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.error(e.getMessage());
        Map<String, Object> params = new ResultParamFactory().add(ResultKey.MESS, e.getMessage()).build();
        ResponseResult failureResponse = new ResponseResult(false, HttpStatus.BAD_REQUEST, params);
        CommonUtil.jsonResponse(response, objectMapper.writeValueAsString(failureResponse));
    }
}
